import axios from 'axios';
import axiosAdapterUniapp from 'axios-adapter-uniapp'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建一个 axios 实例  
const service = axios.create({
	baseURL: 'http://localhost:3000', // url = base url + request url  
	adapter: axiosAdapterUniapp,  // 使用 uniapp 适配器
	timeout: 5000 // 请求超时时间  
});

// 请求拦截器  
service.interceptors.request.use(
	config => {
		const accessToken = uni.getStorageSync('accessToken') 
		if (accessToken) {
			config.headers.Authorization = accessToken
		}
		// 在发送请求之前做些什么  
		return config;
	},
	error => {
		// 对请求错误做些什么  
		return Promise.reject(error);
	}
);

// 响应拦截器  
service.interceptors.response.use(
	response => {
		// 对响应数据做点什么  
		return response.data;
	},
	async error => {
			const originalRequest = error.config
			if ( error.stack === 401 && !originalRequest._retry) {
				originalRequest._retry = true
				try {
					uni.setStorageSync('accessToken', error.response.data.accessToken)
					uni.setStorageSync('refreshToken', error.response.data.refreshToken)

					originalRequest.headers.Authorization = error.response.data.accessToken
					originalRequest.headers.pass = error.response.data.refreshToken
					return response(originalRequest)
				} catch (error) {
					return Promise.reject(error)
				};
			}
			console.log(error,'123');
			uni.navigateTo({ url: '/pages/LoginPage/LoginPage' })
			return Promise.reject(error)
		},
		error => {
			// 对响应错误做点什么  
			return Promise.reject(error);
		}
);

service.defaults.headers.common['Authorization'] = uni.getStorageSync('accessToken')
service.defaults.headers.common['pass'] = uni.getStorageSync('refreshToken')


// ... 其他请求方法
export default service;